package com.ruoyi.net.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.constant.UdpConstants;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.service.INetElementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

//@Component
public class PingTask {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static int PORT = 7889;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private RedisCache redisCache;

    public PingTask() {

    }

    // 定时执行的方法，每隔一定时间（这里设置为5秒，可根据需求调整）去Ping设备并获取状态
    @Scheduled(fixedDelay = 5000)
    public void pingDevices() {
        Collection<String> keys = redisCache.keys(CacheConstants.NET_ELEMENT_KEY + "*");
        for (String key : keys) {
            NetElement netElement = netElementService.getCacheObject(key.replaceAll(CacheConstants.NET_ELEMENT_KEY, ""));
            if (netElement != null
                    && !"2".equalsIgnoreCase(netElement.getDelFlag())
            && StringUtils.isNotEmpty(netElement.getIp())) {
                boolean isOnline = pingDevice(netElement.getIp());
                // 如果ping不通就更新
                if (!isOnline) {
                    netElement.setDisplayStatus("0");
                    // 更新网元状态
                    netElementService.updateNetElement(netElement);
                }
            }
            /*// 推送网元 todo
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                logger.error("PING Thread sleep error: {}", e.getMessage());
            }*/
        }
    }

    private boolean pingDevice(String deviceIp) {
        int successCount = 0;
        try {

            InetAddress inetAddress = InetAddress.getByName(deviceIp);
            for (int i = 0; i < UdpConstants.PING_COUNT; i++) {
                if (!inetAddress.isReachable(UdpConstants.PING_TIMEOUT)) {
                    successCount++;
                }
            }
            return successCount < 4;
        } catch (IOException e) {
            logger.error("Ping device {} error: {}", deviceIp, e.getMessage());
            return false;
        }
    }
}